package com.yunxi.service.localService.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunxi.core.base.Constant;
import com.yunxi.core.page.PageHelperPlus;
import com.yunxi.core.service.ServiceImplPlus;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.util.WgrDate;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.dao.order.OrderVehicleCustomerMapper;
import com.yunxi.model.order.*;
import com.yunxi.model.sat.HandleVehicle;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.model.vip.StoVehicleExp;
import com.yunxi.model.vip.Vip;
import com.yunxi.order.pojo.*;
import com.yunxi.sat.pojo.HandleVehicleVO;
import com.yunxi.service.localService.OrderActualSalesService;
import com.yunxi.service.localService.OrderCustomerDetailService;
import com.yunxi.service.localService.OrderCustomerService;
import com.yunxi.service.localService.OrderVehicleService;
import com.yunxi.service.localService.sat.HandleVehicleService;
import com.yunxi.service.localService.sto.VehicleOfflineService;
import com.yunxi.service.localService.sto.VehicleStockMService;
import com.yunxi.service.localService.vip.StoVehicleExpService;
import com.yunxi.service.localService.vip.VipService;
import com.yunxi.vip.pojo.VipPersonVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 车辆订单 服务实现类
 * </p>
 * @author chenmeng
 * @since 2019-05-07
 */
@Service(value = "orderVehicleServiceImpl")
public class OrderVehicleServiceImpl extends ServiceImplPlus<OrderVehicleCustomerMapper, OrderVehicle> implements OrderVehicleService {

    @Autowired
    @Qualifier(value = "vehicleStockMServiceImpl")
    VehicleStockMService vehicleStockService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineService;

    @Autowired
    @Qualifier(value = "orderCustomerServiceImpl")
    OrderCustomerService orderCustomerService;

    @Autowired
    @Qualifier(value = "orderCustomerDetailServiceImpl")
    OrderCustomerDetailService orderCustomerDetailService;

    @Autowired
    @Qualifier(value = "orderActualSalesServiceImpl")
    OrderActualSalesService orderActualSalesService;

    @Autowired
    @Qualifier(value = "stoVehicleExpServiceImpl")
    StoVehicleExpService stoVehicleExpService;

    @Autowired
    @Qualifier("codeCreateServiceImpl")
    CodeCreateServiceImpl codeCreateService;

    @Autowired
    @Qualifier(value = "handleVehicleServiceImpl")
    HandleVehicleService handleVehicleService;

    @Autowired
    @Qualifier(value = "vipServiceImpl")
    VipService vipService;

    @Override
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderForPage(OrderVehicleManagerDetailsReqVO vo, int pageIndex, int pageSize) {
        PageHelper.startPage(pageIndex,pageSize);
        List<OrderVehicleManagerDetailsRespVO> details = this.baseMapper.queryOrderForPage(vo);
        PageInfo<OrderVehicleManagerDetailsRespVO> pageInfo = new PageInfo<>(details);
        return pageInfo;
    }

    @Override
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveForPage(OrderVehicleManagerDetailsReqVO vo, int pageIndex, int pageSize) {
        PageHelper.startPage(pageIndex,pageSize);
        List<OrderVehicleManagerDetailsRespVO> details = this.baseMapper.queryOrderApproveForPage(vo);
        PageInfo<OrderVehicleManagerDetailsRespVO> pageInfo = new PageInfo<>(details);
        return pageInfo;
    }

    @Override
    public ApiResult orderExport(OrderVehicleManagerDetailsReqVO vo) {
        return ResponseUtil.ok(baseMapper.orderExport(vo));
    }

    @Override
    public OrderApproveDetails queryOrderApproveDetails(OrderApproveDetailsReqVO vo) {
        return this.baseMapper.queryOrderApproveDetails(vo);
    }

    @Override
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveMatchCarForPage(OrderVehicleManagerDetailsReqVO vo,int pageIndex,int pageSize) {
        PageHelper.startPage(pageIndex,pageSize);
        List<OrderVehicleManagerDetailsRespVO> details = this.baseMapper.queryOrderApproveMatchCarForPage(vo);
        PageInfo<OrderVehicleManagerDetailsRespVO> pageInfo = new PageInfo<>(details);
        return pageInfo;
    }

    @Override
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveCheckForPage(OrderVehicleManagerDetailsReqVO vo,int pageIndex,int pageSize) {
        PageHelper.startPage(pageIndex,pageSize);
        List<OrderVehicleManagerDetailsRespVO> details = this.baseMapper.queryOrderApproveCheckForPage(vo);
        PageInfo<OrderVehicleManagerDetailsRespVO> pageInfo = new PageInfo<>(details);
        return pageInfo;
    }

    @Override
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveCheckForDownload(OrderVehicleManagerDetailsReqVO vo) {
        List<OrderVehicleManagerDetailsRespVO> details = this.baseMapper.queryOrderApproveForPage(vo);
        PageInfo<OrderVehicleManagerDetailsRespVO> pageInfo = new PageInfo<>(details);
        return pageInfo;
    }

    @Override
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApprovePrioritySettingForPage(OrderVehicleManagerDetailsReqVO vo,int pageIndex,int pageSize) {
        PageHelper.startPage(pageIndex,pageSize);
        List<OrderVehicleManagerDetailsRespVO> details = this.baseMapper.queryOrderApprovePrioritySettingForPage(vo);
        PageInfo<OrderVehicleManagerDetailsRespVO> pageInfo = new PageInfo<>(details);
        return pageInfo;
    }

    @Override
    public PageInfo<StockResourceRespVO> queryStockResource(StockOrProductionLineResourceReqVO vo,int pageIndex, int pageSize){
        PageHelper.startPage(pageIndex,pageSize);
        List<StockResourceRespVO> stockResources = this.baseMapper.queryStockResource(vo);
        PageInfo<StockResourceRespVO> pageInfo = new PageInfo<>(stockResources);
        return pageInfo;
    }

    @Override
    public PageInfo<ProductionLineResourceRespVO> queryProductionLineResource(StockOrProductionLineResourceReqVO vo,int pageIndex, int pageSize) {
        PageHelper.startPage(pageIndex,pageSize);
        List<ProductionLineResourceRespVO> resources = this.baseMapper.queryProductionLineResource(vo);
        PageInfo<ProductionLineResourceRespVO> pageInfo = new PageInfo<>(resources);
        return pageInfo;
    }

    @Override
    public OrderVehicleDetailsRespVO queryOrderVehicleDetails(OrderVehicleDetailsReqVO vo) {
        return this.baseMapper.queryOrderVehicleDetails(vo);
    }

    @Override
    public String queryStockAddrByVin(String vin) {
        return baseMapper.queryStockAddrByVin(vin);
    }

    @Override
    public void bandCustomOrderNoByOrderId(OrderVehicle ov) {
        baseMapper.unBandCustomOrderNo(ov.getCustomOrderNo(),ov.getUpdateBy());
        baseMapper.bandCustomOrderNoByOrderId(ov);
    }

    @Override
    public void unBandCustomOrderNo(String orderCustomerNo,String updateBy) {
        baseMapper.unBandCustomOrderNo(orderCustomerNo,updateBy);
    }

    @Override
    public PageInfo<OrderVehicleVO> relatePageList(OrderVehicleVOReq orderVehicleVOReq, Integer pageNum, Integer pageSize) {
        Map map = BeanTools.bean2map(orderVehicleVOReq);
        PageHelperPlus.startPage(pageNum,pageSize);
        List<OrderVehicleVO> list = baseMapper.relatePageList(map);
        PageInfo<OrderVehicleVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 查询已匹配零售订单且未配车的 订货单
     * @return CustomerOrderMatchVO
     */
    @Override
    public List<CustomerOrderMatchVO> queryCustomerOrderMatchVO() {
        return baseMapper.queryCustomerOrderMatchVO();
    }

    @Override
    public List<NoMatchCarOrderForDownloadRespVO> queryNoMatchCarOrderForDownload() {
        return baseMapper.queryNoMatchCarOrderForDownload();
    }


    @Override
    public PageInfo listVehicleDeliveryInfo(OrderVehicleDeliveryReqVO reqVO, Integer pageNum, Integer pageSize) {
        PageHelperPlus.startPage(pageNum,pageSize);
        List<OrderVehicleDeliveryRespVO> list = baseMapper.listVehicleDeliveryInfo(reqVO);
        PageInfo<OrderVehicleDeliveryRespVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo listVehicleInStock(OrderVehicleInStockReqVO reqVO, Integer pageNum, Integer pageSize) {
        PageHelperPlus.startPage(pageNum,pageSize);
        List<OrderVehicleInStockRespVO> list = baseMapper.listVehicleInStock(reqVO);
        PageInfo<OrderVehicleInStockRespVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void updateVehicleInStockStatus(OrderVehicleInStockReqVO reqVO) {
        OrderVehicle orderVehicle = new OrderVehicle();
        orderVehicle.setOrderCarId(reqVO.getOrderCarId());
        orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_DEALER_INSTOCK);//入库
        baseMapper.updateById(orderVehicle);

        //更新仓库状态
        vehicleStockService.updateDealerStock(reqVO.getVin());
    }

    @Override
    public void matchVipOrder(OrderCustomerVO orderCustomerVO) {
        //根据订单所归属的渠道商，查询行政区划，
        OrderVehicle ovv = baseMapper.matchVipOrder(orderCustomerVO.getOrderCustomerNo());

        if(ovv!=null){
            ovv.setCustomOrderNo(orderCustomerVO.getOrderCustomerNo());
            baseMapper.updateById(ovv);

        }
       //根据行政区划查询此下面的大客户订单已审核完成的 订货单 进行更新

        //如果根据渠道商没有找到 就根据所有区找

        //更新零售单号
    }

    @Override
    public void band(String orderCustomerNo, String orderCarId,String addr) {
        //清空历史绑定
        baseMapper.cleanCustomOrderNo(orderCustomerNo);
        OrderVehicle ov = baseMapper.selectById(orderCarId);
        ov.setCustomOrderNo(orderCustomerNo);
        ov.setAddr(addr);
        baseMapper.updateById(ov);
        OrderCustomerVO vo = orderCustomerService.getByOrderCustomerNo(orderCustomerNo);
        StoVehicleExp stoVehicleExp = stoVehicleExpService.getByOrderVehicleId(orderCarId);
        stoVehicleExp.setPartnerCode(vo.getPartnerCode());
        stoVehicleExpService.updateById(stoVehicleExp);
    }

    @Override
    public void unband(String orderCarId) {
        baseMapper.unband(orderCarId);
    }

    @Override
    public void hireInit(String vin) {
        VehicleOffline vo = vehicleOfflineService.getByVin(vin);
        OrderCustomerVO ocv = new OrderCustomerVO();
        ocv.setVin(vin);
        List list = orderCustomerService.listByVo(vin);
        if(list.size()>0){
            vo.setExperienceCount(1);
            vehicleOfflineService.updateById(vo);
        }
    }

    @Override
    public void hireCount(String vin) {
        VehicleOffline vo = vehicleOfflineService.getByVin(vin);
        OrderCustomerVO ocv = new OrderCustomerVO();
        ocv.setVin(vin);
        List list = orderCustomerService.listByVo(vin);
        vo.setExperienceCount(list.size());
        vehicleOfflineService.updateById(vo);
    }

    @Override
    public OrderVehicle queryOrderVehicleByVin(String vin) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("VIN",vin);
        return baseMapper.selectOne(qw);
    }

    @Override
    public OrderVehicle loadByVin(String vin){
        return baseMapper.loadByVin(vin);
    }

    @Override
    public PageInfo<ProductionLineResourceRespVO> pageProductionLineResourceByVehicleCode(StockOrProductionLineResourceReqVO vo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<ProductionLineResourceRespVO> resources = this.baseMapper.pageProductionLineResourceByVehicleCode(vo);
        PageInfo<ProductionLineResourceRespVO> pageInfo = new PageInfo<>(resources);
        return pageInfo;
    }

    @Override
    public PageInfo<StockResourceRespVO> queryStockResourceByVehicleCode(StockOrProductionLineResourceReqVO vo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<StockResourceRespVO> stockResources = this.baseMapper.queryStockResourceByVehicleCode(vo);
        PageInfo<StockResourceRespVO> pageInfo = new PageInfo<>(stockResources);
        return pageInfo;
    }

    @Override
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveCheckForPageVip(OrderVehicleManagerDetailsReqVO vo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<OrderVehicleManagerDetailsRespVO> details = this.baseMapper.queryOrderApproveCheckForPageVip(vo);
        PageInfo<OrderVehicleManagerDetailsRespVO> pageInfo = new PageInfo<>(details);
        return pageInfo;
    }

    @Override
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveCheckExpienceForPage(OrderVehicleManagerDetailsReqVO vo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<OrderVehicleManagerDetailsRespVO> details = this.baseMapper.queryOrderApproveCheckExpienceForPage(vo);
        PageInfo<OrderVehicleManagerDetailsRespVO> pageInfo = new PageInfo<>(details);
        return pageInfo;
    }

    /**
     * Guan 2019-11-27
     * 体验车 根据vin码生成零售订单及实销数据
     * @param vin
     */
    @Override
    public ApiResult createDataForExpience(String vin) {
        //根据vin查询订货单号
        OrderVehicle ov = this.loadByVin(vin);

        if(ov==null) return ResponseUtil.fail(502,"根据vin没有找到对应订货单");

        //如果是体验车 或者 试驾车 需要创建做空数据
        if(ov.getVehiclePurpose()!=1 || StringUtils.isNotEmpty(ov.getVipId())){

            Date curDate = WgrDate.getCurrentDate();
            OrderActualSales oas = new OrderActualSales();

            //如果之前没有绑定过 零售订单 则生成零售订单
                //初始化零售订单信息
                OrderCustomer oc = new OrderCustomer();
                OrderCustomerDetail ocd = new OrderCustomerDetail();
                oc.setVin(vin);
                oc.setOrderCustomerNo(codeCreateService.createCode("BB", "yyyyMMdd", 6));

                oc.setPartnerCode(ov.getPartnerCode());
                oc.setOrderSource(2);

                if(StringUtils.isNotEmpty(ov.getVipId())){
                    oc.setOrderType(2);
                }else{
                    oc.setOrderType(1);
                }

                oc.setNum(1);
                oc.setOrderStatus(3);
                oc.setOrderNo(oc.getOrderCustomerNo());
                oc.setProductPackageId(ov.getCatalogCode());
                oc.setIsHide(1);
                oc.setIsUpload("0");

                //Guan 不能用 VehiclePurpose 来替换BuyType
                if(ov.getVehiclePurpose()==1||ov.getVehiclePurpose()==2){
                    oc.setBuyType(ov.getVehiclePurpose());
                }else if(ov.getVehiclePurpose()==3){
                    oc.setBuyType(4);
                }else{
                    oc.setBuyType(5);
                }
                ocd.setColorCodeIn(ov.getColorCodeIn());
                //关联主单
                ocd.setOrderCustomerNo(oc.getOrderCustomerNo());
                ocd.setOrderNo(ov.getCustomOrderNo());
                ocd.setColorCodeOut(ov.getColorCodeOut());
                ocd.setColorNameIn(ov.getColorNameIn());
                ocd.setColorNameOut(ov.getColorNameOut());
                ocd.setCustomPackCode(ov.getCustomPackCodes());
                ocd.setCustomPackName(ov.getCustomPackNames());
                ocd.setProductCode(ov.getProductCode());
                ocd.setNum(1);
                ocd.setVehicleCode(ov.getCatalogCode());
                ocd.setVehicleName(ov.getSeriesName()+"/"+ov.getCatalogName());
                //初始化实销信息
                orderCustomerService.save(oc);
                orderCustomerDetailService.save(ocd);

            oas.setPartnerCode(oc.getPartnerCode());
            //更新ov的零售订单号
            ov.setCustomOrderNo(oc.getOrderCustomerNo());
            oas.setOrderCustomerNo(ov.getCustomOrderNo());
            oas.setPartnerCode(ov.getPartnerCode());
            oas.setIsBuyServicePack("N");
            oas.setCarSaleStatus("0");
            oas.setIsReported(0);
            oas.setVin(vin);

            oas.setCarUsed(ov.getVehiclePurpose()+"");
            oas.setBrandCode(ov.getSeriesCode());
            oas.setBrandName(ov.getSeriesName());
            oas.setVehicleCode(ov.getCatalogCode());
            oas.setVehicleName(ov.getSeriesName()+"/"+ov.getCatalogName());
            oas.setColorOutCode(ov.getColorCodeOut());
            oas.setColorOutName(ov.getColorNameOut());
            oas.setColorInnerCode(ov.getColorCodeIn());
            oas.setColorInnerName(ov.getColorNameIn());
            oas.setCreateRecordDate(WgrDate.getCurrentDateStr());
            oas.setSaleInternetNo(ov.getPartnerCode());
            oas.setSaleInternetName(ov.getPartnerName());
            if(ov.getSettlementPrice()!=null)
            oas.setSalePrice(ov.getSettlementPrice().toString());

            VehicleOffline vehicleOffline = vehicleOfflineService.getByVin(vin);
            if(vehicleOffline != null){
                if(StringUtils.isNotEmpty(vehicleOffline.getMotorCode())){
                    oas.setMotorNo(vehicleOffline.getMotorCode());
                }
                if(StringUtils.isNotEmpty(vehicleOffline.getElectronicControl())){
                    oas.setEnguneNo(vehicleOffline.getElectronicControl());
                    oas.setElectronicControl(vehicleOffline.getElectronicControl());
                }
                if(StringUtils.isNotEmpty(vehicleOffline.getBettaryCode())){
                    oas.setBettaryCode(vehicleOffline.getBettaryCode());
                }
        }

            oas.setCustomPackCode(ov.getCustomPackCodes());
            oas.setCustomPackName(ov.getCustomPackNames());
            oas.setInterchange(curDate);
            if(ov.getVehiclePurpose()==1){
                oas.setCarUsed("1");
            }
            else if(ov.getVehiclePurpose()==2){
                oas.setCarUsed("2");
            }else if(ov.getVehiclePurpose()==3){
                oas.setCarUsed("3");
                oas.setCustomerType("2");
            }
            //oas.set

            if(StringUtils.isNotEmpty(ov.getVipId())){
                //根据大客户信息获取 企业信息字段信息
                Vip vip = vipService.getById(ov.getVipId());
                oas.setUnitSocialCreditCode(vip.getCertNo());
                oas.setIdNumber(vip.getCertNo());
                oas.setIdType("4");
                oas.setCompanyPhone(vip.getPhone());
                oas.setCompanyAddr(vip.getProvinceName()+vip.getCityName()+vip.getRegionName()+vip.getVipAddr());
                oas.setPhone(vip.getPhone());
                oas.setSaleProvinceName(vip.getProvinceName());
                oas.setSaleProvince(vip.getProvinceCode());
                oas.setSaleCity(vip.getCityCode());
                oas.setSaleCityName(vip.getCityName());
                oas.setSaleCountry(vip.getRegionCode());
                oas.setSaleCountryName(vip.getRegionName());
                oas.setCustomerType("2");
                oas.setLegalPerson(vip.getLinkman());
                oas.setBuyerPerson(vip.getLinkman());
                oas.setSaleAssist("暂无");
                oas.setSex("1");
                if(StringUtils.isNotEmpty(vip.getPersons())){
                    List<VipPersonVO> personList = JSONArray.parseArray(vip.getPersons(), VipPersonVO.class);
                    if(personList!=null&&personList.size()>0)
                    {
                        oas.setBuyerPerson(personList.get(0).getName());
                    }
                }
            }else{

            }

            orderActualSalesService.save(oas);

            if(StringUtils.isNotEmpty(ov.getVipId())){

                HandleVehicleVO his = handleVehicleService.getByOrderCustomerNo(ov.getCustomOrderNo());
                if(his==null)
                {
                    HandleVehicle handleVehicle = new HandleVehicle();
                    handleVehicle.setPartnerCode(ov.getPartnerCode());
                    handleVehicle.setOrderCustomerNo(ov.getCustomOrderNo());
                    //handleVehicle.setCustomerNo(oc.getCustomerNo());
                    handleVehicle.setHandleTime(curDate);
                    //handleVehicle.setHandleUser(oc.getHandleUser());
                    handleVehicle.setSalesConsultantNo("");
                    handleVehicleService.saveOrUpdate(handleVehicle);
                }
            }

            this.updateById(ov);
        }
        return ResponseUtil.ok();
    }

    @Override
    public List<OrderVehicleManagerDetailsRespVO> queryOrderApproveCheckExpienceForDownload(OrderVehicleManagerDetailsReqVO vo) {
        List<OrderVehicleManagerDetailsRespVO> details = this.baseMapper.queryOrderApproveCheckExpienceForPage(vo);
        return details;
    }

}
